import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.ao.quantization import QuantStub, DeQuantStub, fuse_modules, prepare, prepare_qat, convert
import pooling_layers


class QuantizableBasicBlock(nn.Module):
    expansion = 1

    def __init__(self, in_planes, planes, stride=1):
        super(QuantizableBasicBlock, self).__init__()
        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes * self.expansion, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.shortcut = nn.Sequential()
        if stride != 1 or in_planes != self.expansion * planes:
            self.shortcut = nn.Sequential(
                nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(self.expansion * planes),
            )
        self.add = nn.quantized.FloatFunctional()

    def forward(self, x):
        identity = x
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        identity = self.shortcut(identity)
        out = self.add.add(out, identity)
        out = self.relu(out)
        return out

    def fuse_model(self):
        fuse_modules(self, ['conv1', 'bn1', 'relu'], inplace=True)
        fuse_modules(self, ['conv2', 'bn2'], inplace=True)
        if len(self.shortcut) > 0:
            fuse_modules(self.shortcut, ['0', '1'], inplace=True)

class QuantizableResNet(nn.Module):
    def __init__(self, num_blocks, block_type, m_channels=32, feat_dim=40, embed_dim=128, pooling_func="TSTP", two_emb_layer=True):
        super(QuantizableResNet, self).__init__()
        self.quant = QuantStub()
        self.dequant = DeQuantStub()
        self.in_planes = m_channels
        self.feat_dim = feat_dim
        self.embed_dim = embed_dim
        self.stats_dim = int(feat_dim / 8) * m_channels * 8
        self.two_emb_layer = two_emb_layer
        if block_type == "BasicBlock":
            block = QuantizableBasicBlock
        elif block_type == "Bottleneck":
            block = Bottleneck
        else:
            raise ValueError(f"block_type {block_type} not supported !!!")

        self.conv1 = nn.Conv2d(1, m_channels, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(m_channels)
        self.relu = nn.ReLU(inplace=True)
        self.layer1 = self._make_layer(block, m_channels, num_blocks[0], stride=1)
        self.layer2 = self._make_layer(block, m_channels * 2, num_blocks[1], stride=2)
        self.layer3 = self._make_layer(block, m_channels * 4, num_blocks[2], stride=2)
        self.layer4 = self._make_layer(block, m_channels * 8, num_blocks[3], stride=2)
        self.pool = getattr(pooling_layers, pooling_func)(in_dim=self.stats_dim * block.expansion)
        self.pool_out_dim = self.pool.get_out_dim() * 2
        
        # 在自定义实现中替换标准线性层为量化线性层
        print(f"Self.pool_out_dim: {self.pool_out_dim}")
        print(f"Embed_dim: {embed_dim}")
        self.seg_1 = nn.Linear(self.pool_out_dim, embed_dim)
        if self.two_emb_layer:
            self.seg_bn_1 = nn.BatchNorm1d(embed_dim, affine=False)
            self.seg_2 = nn.Linear(embed_dim, embed_dim)
        else:
            self.seg_bn_1 = nn.Identity()
            self.seg_2 = nn.Identity()
        # 设置 QLinear 的 qconfig
        self.pool.qconfig = torch.ao.quantization.get_default_qconfig('fbgemm')
        self.seg_1.qconfig = torch.ao.quantization.get_default_qconfig('fbgemm')
        prepare(self.pool, inplace=True)
        prepare(self.seg_1, inplace=True)
        convert(self.pool, inplace=True)
        convert(self.seg_1, inplace=True)
        
    def _make_layer(self, block, planes, num_blocks, stride):
        strides = [stride] + [1] * (num_blocks - 1)
        layers = []
        for stride in strides:
            layers.append(block(self.in_planes, planes, stride))
            self.in_planes = planes * block.expansion
        return nn.Sequential(*layers)

    def fuse_model(self):
        fuse_modules(self, ['conv1', 'bn1', 'relu'], inplace=True)
        for layer in [self.layer1, self.layer2, self.layer3, self.layer4]:
            for submodule in layer:
                submodule.fuse_model()

    def forward(self, x):
        x = self.quant(x.permute(0, 2, 1).unsqueeze_(1))
        out = self.relu(self.bn1(self.conv1(x)))
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)
        stats = self.pool(out)
        # 打印stats的数据类型
        print(stats.dtype)
        # stats = torch.quantize_per_tensor(stats, scale=0.1, zero_point=0, dtype=torch.quint8)
        embed_a = self.seg_1(stats)
        output = self.dequant(embed_a)
        return output

# Initialize the model
model = QuantizableResNet([3, 4, 6, 3], "BasicBlock")

# Set the model to evaluation mode before fusion
model.eval()

# Fuse the model components
model.fuse_model()

# Apply quantization configuration
model.qconfig = torch.ao.quantization.get_default_qconfig('fbgemm')
model.train()
prepare_qat(model, inplace=True)
convert(model, inplace=True)
# Prepare and convert the model to a quantized version
# model_prepared = prepare(model, inplace=False)
# model_quantized = convert(model_prepared, inplace=False)

# Perform a simple forward pass to verify functionality
x = torch.rand(10, 40, 80)  # Example input tensor
output = model(x)
print(output)
